package com.starblink.login.signin.ui

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.login.LoginResult
import com.guadou.lib_baselib.view.span.dsl.buildSpannableString
import com.starblink.android.basic.appsflyer.AppsflyerManager
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.user.login.FacebookLoginUtils
import com.starblink.android.basic.user.login.GoogleLoginUtils
import com.starblink.android.basic.user.login.LoginManager
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.R
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.login.databinding.ActivitySigninBinding
import com.starblink.rocketreserver.type.LoginChannel

@Route(path = RoutePage.Login.SING_IN)
class SigninActivity : BaseTVMActivity<ActivitySigninBinding, SigninVM>() {
    companion object {
        const val REQUEST_CODE_LOGIN_EMAIL = 101 // 邮箱登录
        const val REQUEST_CODE_LINK_SOCIAL_GUANG_ACCOUNT = 103 // 连接账号
        const val REQUEST_CODE_CREATE_ACCOUNT = 104 // 创建账号
        const val REQUEST_CODE_GOOGLE_LOGIN = 102 // 谷歌登录
    }

    override fun initViewBinding(): ActivitySigninBinding =
        ActivitySigninBinding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        clickHandler()
    }

    private fun clickHandler() {
        viewBinding.loginGoogle.setOnClickListener {
            if(!GoogleLoginUtils.isGooglePlayServicesAvailable(this)){
                toast("Please install Google Play Service first.")
                return@setOnClickListener
            }
            if (GoogleLoginUtils.isLogin()) {
                YYLogUtils.e("用户已登录,先登出在登录")
                GoogleLoginUtils.signOut().addOnCompleteListener {
                    GoogleLoginUtils.signIn(this, REQUEST_CODE_GOOGLE_LOGIN)
                }
            } else {
                YYLogUtils.e("用户未登录，直接登录")
                GoogleLoginUtils.signIn(this, REQUEST_CODE_GOOGLE_LOGIN)
            }
        }
        viewBinding.loginFacebook.setOnClickListener {
            if (FacebookLoginUtils.isLogin()) {
                YYLogUtils.e("用户已登录,先登出在登录", "dss")
                FacebookLoginUtils.signOut()
                facebookSignIn()
            } else {
                YYLogUtils.e("用户未登录，直接登录", "dss")
                facebookSignIn()
            }
        }
        viewBinding.loginEmail.setOnClickListener {
            ARouter.getInstance().build(RoutePage.Login.SING_IN_WITH_EMAIL)
                .navigation(this, REQUEST_CODE_LOGIN_EMAIL)
        }
        viewBinding.loginCreateAccount.buildSpannableString {
            addText("I don't have an account") {
                setColor(CommUtils.getColor(com.starblink.basic.style.R.color.white));
                setClick(useUnderLine = false) {
                    AppsflyerManager.reportRegistration()
                    navigationTo(
                        url = RoutePage.Login.CREATE_ACCOUNT_INPUT_EMAIL,
                        requestCode = REQUEST_CODE_CREATE_ACCOUNT
                    )
                }
            }
        }
    }

    private fun facebookSignIn() {
        FacebookLoginUtils.signIn(
            this,
            object : FacebookCallback<LoginResult> {
                override fun onCancel() {
                    toast(R.string.login_cancel)
                }

                override fun onError(error: FacebookException) {
                    toast(R.string.login_fail)
                }

                override fun onSuccess(result: LoginResult) {
                    YYLogUtils.e("facebookSignIn onSuccess", "dss")
                    viewModel.loginWithThirdParty(LoginChannel.facebook, result.accessToken.token)
                }
            }
        )
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            REQUEST_CODE_LOGIN_EMAIL, REQUEST_CODE_LINK_SOCIAL_GUANG_ACCOUNT, REQUEST_CODE_CREATE_ACCOUNT -> {
                if (resultCode == Activity.RESULT_OK) {
                    this.setResult(Activity.RESULT_OK, Intent().putExtra("isLogin", true))
                    this.finish()
                }
            }
            REQUEST_CODE_GOOGLE_LOGIN -> {
                if (resultCode == RESULT_OK) {
                    GoogleLoginUtils.handleGoogleSignInResult(
                        data,
                        onSuccess = {
                            if (it.email.isNullOrEmpty()) {
                                toast(CommUtils.getString(R.string.login_fail))
                            } else {
                                GoogleLoginUtils.fetchGoogleAccessToken(it.email!!) { accessToken ->
                                    if (accessToken.isNullOrEmpty()) {
                                        toast(R.string.login_fail)
                                        return@fetchGoogleAccessToken
                                    }
                                    viewModel.loginWithThirdParty(
                                        LoginChannel.google,
                                        accessToken!!
                                    )
                                }
                            }
                        },
                        onFail = {
                            toast(CommUtils.getString(R.string.login_fail))
                        }
                    )
                }
            }
        }
    }

    override fun initObservable() {
        super.initObservable()
        viewModel.linkSocialGuangAccountLiveData.observe(this) {
            navigationTo(
                url = RoutePage.Login.LINK_SOCIAL_GUANG_ACCOUNT,
                requestCode = SigninActivity.REQUEST_CODE_LINK_SOCIAL_GUANG_ACCOUNT
            ) {
                withObject(LoginManager.KEY_THIRD_LOGIN_ACCOUNT, it)
            }
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            setResult(Activity.RESULT_OK, Intent().putExtra("isLogin", false))
            finish()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    // ARouter.getInstance().build(RoutePage.Login.SING_IN_WITH_EMAIL)
    //                .navigation(this, 101, object :
    //                    NavigationCallback {
    //                    override fun onFound(postcard: Postcard) {
    //                        YYLogUtils.d("${postcard}")
    //                    }
    //
    //                    override fun onLost(postcard: Postcard) {
    //                        YYLogUtils.d("${postcard}")
    //                    }
    //
    //                    override fun onArrival(postcard: Postcard) {
    //                        YYLogUtils.d("${postcard}")
    //                    }
    //
    //                    override fun onInterrupt(postcard: Postcard) {
    //                        YYLogUtils.d("${postcard}")
    //                    }
    //                }
}